package com.xiaoy.javamaildemo.formwork.javamail;


import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Address;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeUtility;
import java.io.File;
import java.util.Arrays;
import java.util.List;

/**
 * @ClassName MailMessageHelper
 * @Description TODO
 * @Author xiaoying
 * @Date 2022/6/27 17:10
 * @Version V1.0.0
 */
public class MailMessageHelper {

    public static MailMessageHelper INSTANCE = new MailMessageHelper();

    private VevorMimeMessage mimeMessage;

    public MailMessageHelper createMimeMessage(IMail mailContext) throws Exception {
        mimeMessage = new VevorMimeMessage(mailContext.getSession());
        return this;
    }

    public  MailMessageHelper setSubject(String subject) throws MessagingException {
        mimeMessage.setSubject(subject);
        return this;
    }

    public  MailMessageHelper setFrom(String from) throws MessagingException {
        mimeMessage.setFrom(from);
        return this;
    }

    public  MailMessageHelper setRecipient(String receiveMail,String personal) throws Exception {
        mimeMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(receiveMail, personal, "UTF-8"));
        return this;
    }

    public  MailMessageHelper setRecipients(List<Address> receiveMail) throws Exception {
        Address[] objects = (Address[]) receiveMail.toArray();
        mimeMessage.addRecipients(Message.RecipientType.TO, objects);
        return this;
    }
    public MailMessageHelper setContext(String text) throws MessagingException {
        mimeMessage.setContent(text,"text/html;charset=UTF-8");
        return this;
    }

    public MailMessageHelper addAttachment(File file) throws Exception {
        addAttachment(Arrays.asList(file));
        return this;
    }

    public MailMessageHelper addAttachment(List<File> listFile) throws Exception {
        MimeMultipart mimeMultipart = new MimeMultipart();
        for (File file : listFile) {
            MimeBodyPart image = new MimeBodyPart();
            DataHandler dh = new DataHandler(new FileDataSource(file));
            image.setDataHandler(dh);
            image.setFileName(MimeUtility.encodeText(dh .getName()));
            mimeMultipart.addBodyPart(image);
        }
        mimeMessage.setContent(mimeMultipart);
        return this;
    }
    public VevorMimeMessage build() throws MessagingException {
        mimeMessage.saveChanges();
        return mimeMessage;
    }
}
